package com.crrc.sandameter.common

import android.preference.PreferenceManager
import com.crrc.sandameter.AppContext

object SPUtil {

    private var sharedPreferences =
        PreferenceManager.getDefaultSharedPreferences(AppContext.getContext())
    private var editor = sharedPreferences.edit()


    /**
     * 保存数据的方法，拿到数据保存数据的基本类型，然后根据类型调用不同的保存方法
     *
     * @param key
     * @param obj
     */
    fun put(key: String, obj: Any) {
        when (obj) {
            is String -> editor.putString(key, obj).apply()
            is Int -> editor.putInt(key, obj).apply()
            is Boolean -> editor.putBoolean(key, obj).apply()
            is Float -> editor.putFloat(key, obj).apply()
            is Long -> editor.putLong(key, obj).apply()
            else -> editor.putString(key, obj.toString()).apply()
        }
    }

    /**
     * 获取保存数据的方法，我们根据默认值的到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param key           键的值
     * @param defaultObject 默认值
     * @return
     */

    fun get(key: String, defaultObject: Any): Any {
        return when (defaultObject) {
            is String -> sharedPreferences.getString(key, defaultObject) ?: ""
            is Int -> sharedPreferences.getInt(key, defaultObject)
            is Boolean -> sharedPreferences.getBoolean(key, defaultObject)
            is Float -> sharedPreferences.getFloat(key, defaultObject)
            is Long -> sharedPreferences.getLong(key, defaultObject)
            else -> sharedPreferences.getString(key, null) ?: ""
        }
    }

    /**
     * 移除某个key值已经对应的值
     *
     * @param key
     */
    fun remove(key: String) {
        editor.remove(key)
        editor.apply()
    }

    /**
     * 清除所有的数据
     */
    fun clear() {
        editor.clear()
        editor.apply()
    }

    /**
     * 查询某个key是否存在
     *
     * @param key
     * @return
     */
    operator fun contains(key: String): Boolean {
        return sharedPreferences.contains(key)
    }

    /**
     * 返回所有的键值对
     *
     * @return
     */
    val all: Map<String, *>
        get() = sharedPreferences.all
}